﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;


namespace Excel2Word
{
    public class ExcelOperation
    {


        /// <summary>
        /// 获得用户打开的当前活动状态EXCEL进程
        /// </summary>
        /// <returns></returns>
        // Word.Application
        public static dynamic GetActiveExcel()
        {
            dynamic _app = null;
            try
            {
                _app = (dynamic)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            }
            catch
            {
            }
            return _app;

        }

        /// <summary>
        /// 根据全路径名称打开EXCEL文件，并获得对象
        /// </summary>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static dynamic GetWorkBookByFullName(string fullName,bool createNewApp = false)
        {
            Application objExcel =createNewApp ? null : GetActiveExcel();
            try
            {
                Boolean isnull = true;
                try
                {
                    isnull = (objExcel == null);
                }
                catch
                {
                    objExcel.Visible = true;
                    isnull = (objExcel == null);
                }
                if (isnull)
                {
                    Type type = Type.GetTypeFromProgID("Excel.Application");
                    objExcel = (Application)Activator.CreateInstance(type);
                    objExcel.Visible = true;//new Microsoft.Office.Interop.Word.Application();  
                }
                else
                {
                    //获取Excel Workbook
                    foreach (dynamic doc in objExcel.Workbooks)
                    {
                        if (doc.FullName == fullName)
                        {
                            return doc;
                        }
                    }
                }
                return objExcel.Workbooks.Open(fullName);
            }
            catch { }

            return null;
        }

    }
}
